package com.jx.db137.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jx.db137.common.JwtUtils;
import com.jx.db137.common.R;
import com.jx.db137.entity.Menu;
import com.jx.db137.entity.User;
import com.jx.db137.service.UserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

/**
 * @author jx
 * @version 1.0
 * @Description
 * @date 2024/12/24 11:51
 */
@CrossOrigin(origins = "*")
@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @GetMapping("selectUserMenu")
    public R selectUserMenu(@RequestHeader("token") String token){
        System.out.println("token = " + token);
        //解析token,获取用户信息id
        Integer userid= JwtUtils.getJwtToken(token,"userid");

        List<Menu> menuList=userService.selectUserMenuByUserId(userid);
        User user=userService.selectUser(userid);

        return new R().addData("menuList",menuList).addData("user",user);
    }

    @PostMapping("registerUser")
    public int registerUser(@RequestBody User user){
       return userService.registerUser(user);
    }

    @PostMapping("loginUser")
    public R getUser(@RequestBody User user){
        QueryWrapper queryWrapper=new QueryWrapper<>();
        queryWrapper.setEntity(user);
        User u = userService.getOne(queryWrapper);
        if(u!=null) {
            //生成token
            HashMap<String, Object> map = new HashMap<>();
            map.put("userid",u.getId());
            String jwtToken = JwtUtils.createJwtToken(map);
            System.out.println("jwtToken = " + jwtToken);
            return new R().addData("token",jwtToken);
        }
        return new R().setMsgerr("出错了").setCode(500);
    }

    //查看
    @GetMapping("userList")
    public R userList(){
        return new R().addData("userList",userService.list());
    }




}
